<?php
/**
 * Created by PhpStorm.
 * 订单配送时间处理
 * User: caicm
 * Date: 2017/11/28
 * Time: 14:44
 */

namespace SDXApi\Service;


use Think\Log;

class OrderDistributionTimeService {

    /**
     * 订单配送时间处理 处理区域配送时间订单峰值、是否超时免单处理
     * Created By caicm
     * @param $distribution_time 配送时间
     * @param int $arrival_type 0 ：当日达  1：次日达
     * @param $wdr_id 区域id
     * @return mixed
     */
    public function get_distributie_time($distribution_time, $arrival_type=0, $wdr_id){
        $uid = I('post.uid');
        if(S('women_day_activity_'.$uid)){
            return $this->activity_distributie_time($distribution_time, $wdr_id);
        }

        $distribution_time_array['tomorrow'] =array();
        $distribution_time_array['today'] =array();

        //区域订单峰值
        $order_peak = $this->get_wdr_order_peak($wdr_id);
        //当前时间段的区域订单数量
        $order_total = S('order_best_time_num');
        //次日达区域 从明天开始
        $day = $arrival_type ? 1 : 0;

        while (true){
            $data = array();
            $time = strtotime("+{$day} day");
            $order_best_time_num = $order_total[date("Ymd", $time)];
            $date = date("Y-m-d", $time);
            $date_day = date("m月d日", $time);
            array_unique($distribution_time);
            foreach ($distribution_time as $key=>$value){
                $closing_time = str_replace(":","",$value['closing_time']);
                $start_time = str_replace(":","",$value['start_time']);
                $now_hour = date('H',time()).date('i',time());

                $best_time = $this->get_best_time($date, $value['start_time'], $value['end_time']);
                $order_num = $order_best_time_num[$wdr_id.'-'.$best_time]; //当前时间段订单数量

                $peak_num = $order_peak[$value['id']]['order_peak'];  //订单峰值配置
                $is_free_single = $order_peak[$value['id']]['is_free_single']; //是否超时免单

                if($order_num >= $peak_num && $peak_num > 0){
                    continue;
                }

                //当天
                if($day == 0){
                    if ($closing_time > $now_hour && $start_time > $closing_time) {
                        $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, 0);
                    }
                    $title = '当天送达';
                }else{
                    if($start_time>$closing_time){
                         $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day);
                    }
                    $title = $date_day;
                }

                if ($start_time < $closing_time && $day != 0) {
                    //开始时间大于截单时间，将时间定位次日
                    $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, 0);
                }

            }

            if(!$distribution_time_array['today'] && $data){
                $distribution_time_array['today'] = $data;
                $distribution_time_array['today_title'] = $title;
            }else{
                $distribution_time_array['tomorrow'] = $data;
            }

            $distribution_time_array['tomorrow_title'] = $title;

            if($distribution_time_array['today'] && $distribution_time_array['tomorrow']){
                break;
            }

            $day++;
        }

        return $distribution_time_array;
    }

    protected function activity_distributie_time($distribution_time, $wdr_id)
    {
        $distribution_time_array['tomorrow'] =array();
        $distribution_time_array['today'] =array();

        $activity_date = array(
            '2018-03-06',
            '2018-03-07',
            '2018-03-08',
        );

        $today_time = strtotime(date('Y-m-d'));
        foreach ($activity_date as $v) {
            $time = strtotime($v);
            $date_day = date("m月d日", $time);
            if ($today_time > $time) {
                continue;
            }

            if($today_time == $time){
                $day = 0;
                $title = '当天送达';
            }else{
                $day = 1;
                $title = $date_day;
            }

            $data = $this->get_test($day, $time, $distribution_time, $wdr_id);

            if(empty($distribution_time_array['tomorrow']) && $distribution_time_array['today']){
                $distribution_time_array['tomorrow'] = $data;
                $distribution_time_array['tomorrow_title'] = $title;
            }

            if(empty($distribution_time_array['today'])){
                $distribution_time_array['today'] = $data;
                $distribution_time_array['today_title'] = $title;
            }


            if($distribution_time_array['today'] && $distribution_time_array['tomorrow']){
                break;
            }
        }

        return $distribution_time_array;
    }

    /**
     * @author Min
     * @param $day
     * @param $time
     * @param $distribution_time
     * @param $wdr_id
     * @return array
     */
    protected function get_test($day, $time, $distribution_time, $wdr_id){
        //区域订单峰值
        $order_peak = $this->get_wdr_order_peak($wdr_id);

        //当前时间段的区域订单数量
        $order_total = S('order_best_time_num');

        $data = array();
        $order_best_time_num = $order_total[date("Ymd", $time)];
        $date = date("Y-m-d", $time);
        $date_day = date("m月d日", $time);

        foreach ($distribution_time as $key=>$value){
            $closing_time = str_replace(":","",$value['closing_time']);
            $start_time = str_replace(":","",$value['start_time']);
            $now_hour = date('H',time()).date('i',time());

            $best_time = $this->get_best_time($date, $value['start_time'], $value['end_time']);
            $order_num = $order_best_time_num[$wdr_id.'-'.$best_time]; //当前时间段订单数量

            $peak_num = $order_peak[$value['id']]['order_peak'];  //订单峰值配置
            $is_free_single = $order_peak[$value['id']]['is_free_single']; //是否超时免单

            if($order_num >= $peak_num && $peak_num > 0){
                continue;
            }

            //当天
            if($day == 0){
                if ($closing_time > $now_hour && $start_time > $closing_time) {
                    $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, 0);
                }
            }else{
                if($start_time>$closing_time){
                    $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day);
                }
            }

            if ($start_time < $closing_time && $day != 0) {
                //开始时间大于截单时间，将时间定位次日
                $data[] = $this->get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, 0);
            }

        }

        return $data;
    }

    /**
     * 添加当前区域的时间段订单量缓存
     * Created By caicm
     * @param $wdr_id 区域id
     * @param $best_time_start 配送开始时间
     * @param $best_time    配送结束时间
     * @param int $order_id 订单id
     * @param int $operation 操作类型 [1]加一  [-1]减一
     * @return bool|mixed
     */
    public function add_order_best_time_cache($wdr_id, $best_time_start, $best_time, $order_id=0, $operation=1){
        $key = date("Ymd", $best_time_start);
        $date = date("Ymd");

        //区域订单数量
        $order_num = S('order_best_time_num');
        if($operation == 1){
            //当前区域的时间段缓存加一
            $order_num[$key]["{$wdr_id}-{$best_time_start}-{$best_time}"]++;
            //删除过期的数据（昨天及之前）
            foreach ($order_num as $k=>$v){
                if($k < $date){
                    unset($order_num[$k]);
                }
            }
        }elseif ($operation == -1){
            //当前区域的时间段缓存减一
            $order_num[$key]["{$wdr_id}-{$best_time_start}-{$best_time}"]--;
        }else{
            return false;
        }

        S('order_best_time_num', $order_num);

        $order_num['test'] = "{$order_id}-[{$operation}]-{$wdr_id}-{$best_time_start}-{$best_time}";
        $this->write_log(json_encode($order_num), 'order_best_time_cache');
    }

    /**
     * 获取当前区域的时间段的段订单量缓存
     * @param $wdr_id
     * @param $best_time_start
     * @param $best_time
     * @return mixed
     */
    public function get_best_time_order_peak($wdr_id, $best_time_start, $best_time){
        $key = date("Ymd", $best_time_start);
        //区域订单数量
        $order_num = S('order_best_time_num');
        return $order_num[$key]["{$wdr_id}-{$best_time_start}-{$best_time}"];
    }

    /**
     * @param $date
     * @param $start_time
     * @param $end_time
     * @return string
     */
    protected function get_best_time($date, $start_time, $end_time){
        $best_time_start = strtotime($date." ". $start_time);
        $best_time = strtotime($date." ". $end_time);
        return $best_time_start.'-'.$best_time;
    }

    /**
     * 获取时间转换格式
     * Created By caicm
     * @param $order_num
     * @param $peak_num
     * @param $is_free_single
     * @param $best_time
     * @param $date_day
     * @param $value
     * @param $day
     * @param int $tomorrow
     * @return array
     */
    protected function get_time($order_num, $peak_num, $is_free_single, $best_time, $date_day, $value, $day, $tomorrow=1){
        $title = '明日';
        if($day==0 && $tomorrow==0){
            $title = $date_day = '今日';
        }
        return array(
            "order_num" => $order_num,
            "order_peak" => $peak_num,
            "value" => $best_time,
            "title" => "{$date_day} {$value['start_time']} - {$value['end_time']}",
            'closing'	=>	$title.$value['closing_time'],
            'is_free_single' => $is_free_single?$is_free_single:0
        );
    }

    /**
     * 获取区域订单峰值
     * Created By caicm
     * @param $wdr_id
     * @return mixed
     */
    protected function get_wdr_order_peak($wdr_id){
        $where = array(
            'wdr_id' => $wdr_id
        );
        $field = 'order_peak,is_free_single,time_id';
        $data = M('warehouse_deliver_region_order_peak')->field($field)->where($where)->select();

        $order_peak = array();
        foreach ($data as $key=>$val){
            $order_peak[$val['time_id']] = array(
                'order_peak' => $val['order_peak'],
                'is_free_single' => $val['is_free_single'],
            );
        }

        return $order_peak;
    }

    /**
     * 获取区域订单峰值
     * Created By caicm
     * @param $wdr_id
     * @param $time_id
     * @return mixed
     */
    public function get_wdr_order_peak_info($wdr_id, $time_id)
    {
        $where = array(
            'wdr_id' => $wdr_id,
            'time_id' => $time_id
        );
        $field = 'order_peak,is_free_single';
        return M('warehouse_deliver_region_order_peak')->field($field)->where($where)->find();

    }

    /**
     * 添加到 订单超时免单记录扩展表
     * @param $order_id
     */
    public function add_order_free_single($order_id){
        $num = $this->check_order_free_single($order_id);
        if(!$num){
            $data = array('order_id' => $order_id);
            M('order_info_free_single')->data($data)->add();
        }
    }

    /**
     * 检查订单是否超时免单
     * @param $order_id
     * @return mixed
     */
    public function check_order_free_single($order_id){
        $where = array('order_id' => $order_id);
        return M('order_info_free_single')->where($where)->count('order_id');
    }


    /**
     * 添加到订单超时处理表
     * @param $order_id
     * @param $position
     */
    public function add_order_info_overtime($order_id, $position=1){
        $order = M('order_info_free_single')
                    ->alias('s')
                    ->field('o.confirm_time,o.best_time')
                    ->join('sdx_order_info o on s.order_id=o.order_id')
                    ->where("s.order_id={$order_id} and (o.confirm_time+28800)>best_time")
                    ->find();

        if($order){
            $order_overtime = M('order_info_overtime')->where(array('order_id'=>$order_id))->count('order_id');
            if(!$order_overtime){
                $data = array(
                    'order_id' => $order_id,
                    'position' => $position,
                    'add_time' => gmtime()
                );
                M('order_info_overtime')->data($data)->add();
            }
        }
    }

    /**
     * 订单超时处理
     * @param $position
     * @return int
     */
    public function order_overtime($position){
        $best_time_start = strtotime("-3 day");
        $best_time = time();

        $sql = "SELECT
                    o.order_id
                FROM
                    sdx_order_info_free_single AS f
                LEFT JOIN sdx_order_info AS o ON f.order_id = o.order_id
                LEFT JOIN sdx_order_info_overtime AS v ON f.order_id = v.order_id
                WHERE
                    v.order_id IS NULL
                AND o.shipping_status !=2
                And o.pay_status in (2,3)
                AND o.196_admin_id=0
                AND {$best_time} > o.best_time
                AND o.best_time_start > {$best_time_start}";

        $order_list = M()->query($sql);

        foreach ($order_list as $key=>$val){
            $val['position'] = $position;
            $val['add_time'] = gmtime();
            M('order_info_overtime')->data($val)->add();
        }

        return count($order_list);

    }

    /**
     * 延时订单-超时免单处理
     * Created By caicm
     * @param $order_id
     * @param $wdr_id
     * @param $best_time_start
     * @param $best_time
     */
    public function delay_order_free_single($order_id, $wdr_id, $best_time_start, $best_time){
        $start_time = date('H:i', $best_time_start);
        $end_time = date('H:i', $best_time);
        $map = array('order_id' => $order_id);

        //获取所选时间段是否设置超时免单
        $sql = "SELECT
                    p.is_free_single
                FROM
                    sdx_warehouse_deliver_region AS w
                LEFT JOIN sdx_distribution_time AS d ON w.wdtype = d.mode_id
                LEFT JOIN sdx_warehouse_deliver_region_order_peak AS p ON w.id = p.wdr_id
                AND d.id = p.time_id
                WHERE
                    w.id = {$wdr_id}
                AND d.start_time = '{$start_time}'
                AND d.end_time = '{$end_time}'";
        $row = M()->query($sql);
        $row = current($row);

        //查询修改之前订单 时间段是否开启超时免单
        $check_order = M('order_info_free_single')->where($map)->count('order_id');
        if($row['is_free_single'] == 1){
            if(!$check_order){
                M('order_info_free_single')->data($map)->add();
            }
        }else{
            if($check_order){
                M('order_info_free_single')->data($map)->delete();
            }
        }

    }

    /**
     * @param $message
     * @param $filename
     */
    public function write_log($message,$filename){
        $log = new Log();
        $destination = C('LOG_PATH').date('y_m_d').'_'.$filename.'.log';

        $log->write($message,'DEBUG','',$destination);
    }
}